package com.rightsidetech.http.controller.agentAdmin.export;

import cn.hutool.core.collection.CollUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.DateUtil;
import com.rightsidetech.commom.utils.ExportExcelUtils;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.BatteryCheckReq;
import com.rightsidetech.system.dtos.request.store.SysStoreInfoReq;
import com.rightsidetech.system.dtos.response.store.SysStoreInfoResp;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.entity.SysAgentLoginInfo;
import com.rightsidetech.system.entity.SysBatteryCheck;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.service.*;
import com.rightsidetech.trade.dtos.request.*;
import com.rightsidetech.trade.dtos.response.*;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.rightsidetech.http.controller.agentAdmin.export
 * @ClassName: ExportCommonController
 * @Author: yinj
 * @CreateTime: 2021/10/28 15:27
 * @Description: 代理商品台导出接口
 */
@RestController
@RequestMapping("/agentAdmin/export")
@ShenyuSpringMvcClient(path = "/agentAdmin/export/**")
@Api(tags = "导出表格相关api")
public class AgentAdminExportController extends BaseController {

    @Autowired
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Autowired
    private SysAgentInfoService sysAgentInfoService;
    @Autowired
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysBatteryCheckService sysBatteryCheckService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserLoginInfoService sysUserLoginInfoService;

    @Log
    @GetMapping("/order")
    @ApiOperation("订单信息导出")
    @Auth(bizType = Auth.AGENT)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize","agentId","areaId"})
    public ResponseData exportTdCommodity(TdCommodityOrderListRequest req, String tokenAdmin) {
        Long agentInfoId = sysAgentInfoService.findAgentInfoIdByToken(tokenAdmin);
        if(StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        req.setAgentId(agentInfoId);
        List<TdCommodityUserOrderResp> list = tdCommodityUserOrderService.selectList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"订单编号", "联系人", "总金额（元）","优惠金额（元）","实付金额（元）", "所属门店", "订单类型","下单时间","付款时间","订单状态"};
        for (TdCommodityUserOrderResp resp : list) {

            Object[] obj = new Object[10];
            obj[0] = resp.getOrderNo();
            obj[1] = resp.getUsName();
            obj[2] = resp.getTotalAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[3] = resp.getDiscountAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[4] = resp.getActualAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[5] = resp.getStoreName();
            obj[6] = resp.getOrderType() == 0 ? "上门服务":"到店自取";
            obj[7] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            obj[8] = DateUtil.getDate(resp.getPayTime(), "yyyy-MM-dd HH:mm:ss");
            String orderStatus = "";
            switch (resp.getOrderStatus()){
                case 0:
                    orderStatus = "待付款";
                    break;
                case 1:
                    orderStatus = "待接单";
                    break;
                case 2:
                    orderStatus = "已完成";
                    break;
                case 3:
                    orderStatus = "售后";
                    break;
                case 4:
                    orderStatus = "退款";
                    break;
                case -1:
                    orderStatus = "取消订单";
                default:
                    break;
            }
            obj[9] = orderStatus;
            dataList.add(obj);
        }
        String title = "订单列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }


    @Log
    @GetMapping("/store")
    @ApiOperation("门店信息导出")
    @Auth(bizType = Auth.AGENT)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize","agentInfoId","areaId"})
    public ResponseData exportStoreList(SysStoreInfoReq req, String tokenAdmin) {
        Long agentInfoId = sysAgentInfoService.findAgentInfoIdByToken(tokenAdmin);
        if(StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        req.setAgentInfoId(agentInfoId);
        List<SysStoreInfoResp> list = sysStoreInfoService.exportStoreList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"门店名称", "负责人", "手机号","门店等级","地址","状态","店铺码"};
        for (SysStoreInfoResp resp : list) {

            Object[] obj = new Object[8];
            obj[0] = resp.getStoreName();
            obj[1] = resp.getStoreBoss();
            obj[2] = resp.getConnectWay();
            obj[3] = resp.getGradeName();
            obj[4] = resp.getAdress();
//            BigDecimal point = BigDecimal.ZERO;
//            if (!StringUtils.isEmpty(resp.getPoint())){
//                point  = resp.getPoint();
//            }
//            obj[6] = point.setScale(0, BigDecimal.ROUND_DOWN ); // 向下取整
            if(resp.getStatus() != null){
                switch (resp.getStatus()){
                    case 1:
                        obj[5] = "营业中";
                        break;
                    case -1:
                        obj[5] = "已关闭";
                        break;
                    default:
                        break;
                }
            }
            obj[6] = resp.getStoreNumber();

            dataList.add(obj);
        }
        String title = "门店列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/orderBill")
    @ApiOperation("商城账单导出")
    @Auth(bizType = Auth.AGENT)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize","agentId","areaId"})
    public ResponseData exportTdCommodityBill(TdCommodityTradeOrderReq req, String tokenAdmin) {
        req.setPageNo(1);
        req.setPageSize(15);
        Long agentInfoId = sysAgentInfoService.findAgentInfoIdByToken(tokenAdmin);
        if(StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        SysAgentInfo agentInfoById = sysAgentInfoService.findAgentInfoById(agentInfoId);
        if(agentInfoById.getAreaId() != 0){
            req.setAreaId(agentInfoById.getAreaId());
        }

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<TdCommodityTradeOrderResp> list = tdCommodityUserOrderService.findCommodityBillList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"订单编号", "支付单号", "总金额（元）", "优惠金额（元）", "实付金额（元）", "状态", "付款时间","退款时间"};
        for (TdCommodityTradeOrderResp resp : list) {

            Object[] obj = new Object[10];
            obj[0] = resp.getOrderNo();
            obj[1] = resp.getThirdOrderNo();
            obj[2] = resp.getAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[3] = resp.getDiscountAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[4] = resp.getActualAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[5] = resp.getOrderStatus() == 0 ? "已支付" : "退款";
            obj[6] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            obj[7] = DateUtil.getDate(resp.getRefundTime(), "yyyy-MM-dd HH:mm:ss");
            dataList.add(obj);
        }
        String title = "商城账单" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/batteryCheck")
    @ApiOperation("电池检测导出")
    @Auth(bizType = Auth.AGENT)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize","agentId"})
    public ResponseData exportBatteryCheck(BatteryCheckReq request, String tokenAdmin) {
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentInfoId = sysAgentInfoService.findAgentInfoIdByToken(tokenAdmin);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        request.setAgentId(agentInfoId);
        List<SysBatteryCheck> list = sysBatteryCheckService.exBatteryCheck(request);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"门店", "电池名称", "型号","电池编码","提交日期", "质保期", "放电时间(分钟)","检测结果","检测日期","状态"};
        for (SysBatteryCheck resp:list) {
            Object[] obj = new Object[10];
            obj[0] = resp.getStoreName();
            obj[1] = resp.getBatteryName();
            obj[2] = resp.getSpecs();
            obj[3] = resp.getBatteryCode();
            obj[4] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd");
            if(resp.getWarranty() != null){
                switch (resp.getWarranty()){
                    case 1:
                        obj[5] = "换新";
                        break;
                    case 2:
                        obj[5] = "换专";
                        break;
                    case 3:
                        obj[5] = "换维";
                    default:
                        break;
                }
            }
            obj[6] = resp.getDischargeTime();
            if(resp.getCheckResult() != null){
                switch (resp.getCheckResult()){
                    case 1:
                        obj[7] = "电池正常";
                        break;
                    case 2:
                        obj[7] = "可以更换";
                    default:
                        break;
                }
            }
            obj[8] = DateUtil.getDate(resp.getCheckTime(), "yyyy-MM-dd");
            if(resp.getStatus() != null){
                switch (resp.getStatus()){
                    case 0:
                        obj[9] = "待处理";
                        break;
                    case 1:
                        obj[9] = "已完成";
                    default:
                        break;
                }
            }
            dataList.add(obj);
        }
        String title = "电池检测" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @ApiOperation("订单售后列表导出")
    @Auth(bizType = Auth.AGENT)
    @GetMapping("/afterService")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportAfterService(TdCommodityAfterServiceReq req, String tokenAdmin) throws Exception {
        Long loginInfoId = sysAgentInfoService.sysUsercheckToken(tokenAdmin);
        SysAgentLoginInfo loginInfo = sysAgentInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }

        List<TdCommodityAfterPageResp> resps = tdCommodityUserOrderService.selectAfterServiceList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"订单编号", "联系人", "手机号","门店名称","申请时间","售后原因", "售后状态","审核人", "审核时间"};
        List<Object[]> list = new ArrayList<>();
        for (TdCommodityAfterPageResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getUsName();
            objs[2] = resp.getUsPhoneNo();
            objs[3] = resp.getStoreName();
            objs[4] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            objs[5] = resp.getReason();
            //售后状态, 0-待审核, 1-已完成,  -1-拒绝， -2-取消申请
            objs[6] = resp.getStatus() == 0 ? "待审核" : (resp.getStatus() == 1 ? "已完成" : (resp.getStatus() == -1 ? "拒绝" : "取消申请"));
            objs[7] = resp.getStoreLoginName();
            objs[8] = DateUtil.getDate(resp.getCheckedAt(), "yyyy-MM-dd HH:mm:ss");
            list.add(objs);
        }
        String title = "售后申请记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @ApiOperation("订单售后退款导出")
    @Auth(bizType = Auth.AGENT)
    @GetMapping("/afterServiceMoney")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportAfterServiceMoney(TdCommodityAfterServiceMoneyReq req, String tokenAdmin) throws Exception {
        Long loginInfoId = sysAgentInfoService.sysUsercheckToken(tokenAdmin);
        SysAgentLoginInfo loginInfo = sysAgentInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }

        List<TdCommodityAfterServiceMoneyResp> resps = tdCommodityUserOrderService.selectAfterServiceMoneyList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"订单编号", "联系人", "退款总金额(元)","优惠金额(元)","实际退款(元)","门店名称", "订单类型","退款时间"};
        List<Object[]> list = new ArrayList<>();
        for (TdCommodityAfterServiceMoneyResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getUsName();
            objs[2] = StringUtils.isEmpty(resp.getTotalAmount()) ? 0 : resp.getTotalAmount().divide(new BigDecimal(100));
            objs[3] = StringUtils.isEmpty(resp.getDiscountAmount()) ? 0 : resp.getDiscountAmount().divide(new BigDecimal(100));
            objs[4] = StringUtils.isEmpty(resp.getActualAmount()) ? 0 : resp.getActualAmount().divide(new BigDecimal(100));
            objs[5] = resp.getStoreName();
            //售后状态, 0-待审核, 1-已完成,  -1-拒绝， -2-取消申请
            objs[6] = resp.getOrderType() == 0 ? "上门服务" : "到店自取";
            objs[7] = DateUtil.getDate(resp.getUpdatedAt(), "yyyy-MM-dd HH:mm:ss");
            list.add(objs);
        }
        String title = "售后退款记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

}
